<?php

/**
 * This file is part of the People Of Walmart block for Moodle.
 * Copyright (C) 2009-2010 <anonymousmoodler@gmail.com>
 * 
 * The People Of Walmart block is distributed under the terms of the GNU
 * General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version. You should
 * have received a copy of the GNU General Public License along with the People
 * Of Walmart block. If not, see <http://www.gnu.org/licenses/>.
 */

class block_peopleofwalmart extends block_base
{

    function init()
    {
        global $CFG;

        $this->title   = get_string('blockname', 'block_peopleofwalmart');
        $this->version = 2010022500;
        $this->cron    = 300;

        // set some paths
        $this->cache_dir = $CFG->dataroot.'/cache/peopleofwalmart';
        $this->cache_html_file = $this->cache_dir.'/content.html';

        // number of thumbnails to display by default (10 maximum)
        $this->number_of_thumbnails = 4;
        // display captions inline? 1 for yes, 0 for no
        $this->display_captions_inline = 0;
        // number of minutes to cache thumbnails
        $this->thumbnail_cache_time = 1440;

        if (isset($CFG->block_peopleofwalmart_thumbnail_cache_time)) {
            $this->thumbnail_cache_time = 60 * $CFG->block_peopleofwalmart_thumbnail_cache_time;
        }
    }

    function instance_allow_multiple()
    {
        return TRUE;
    }

    function preferred_width()
    {
        return 200;
    }

    // generates the HTML for the block
    function get_content()
    {
        global $CFG;

        if ($this->content !== NULL) {
            return $this->content;
        }

        $this->content = new stdClass;
        $this->content->footer = '<a target="_blank" href="http://www.peopleofwalmart.com/">'.
            'www.peopleofwalmart.com</a>';

        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            if (preg_match('/MSIE (\d)/i', $_SERVER['HTTP_USER_AGENT'], $matches) >	0) {
                if (intval($matches[1]) < 7) {
                    $this->content->text = 'Your browser is not compatible with this block.';
                    return $this->content;
                }
            }
        }

        // if the cache file doesn't exist, call update_cache() to create it
        if (!file_exists($this->cache_html_file)) {
            $this->update_cache();
        }

        $this->content->text = '';

        // if number_of_thumbnails has been configured, get the value
        if (isset($this->config->number_of_thumbnails)) {
            $this->number_of_thumbnails = $this->config->number_of_thumbnails;
        }

        if (isset($this->config->display_captions_inline)
            && $this->config->display_captions_inline == 1
        ) {
            $this->content->text .= '<style type="text/css">'.
                '#inst'.$this->instance->id.' .block_peopleofwalmart_caption { display:block; }'.
                '</style>';
        }

        $this->content->text .= '<center>';

        // read from the cache file
        $cache_fp = fopen($this->cache_html_file, 'r');
        for ($i = 0; !feof($cache_fp) && $i < $this->number_of_thumbnails; $i++) {
            $this->content->text .= fgets($cache_fp);
        }
        fclose($cache_fp);
        unset($cache_fp);

        $this->content->text .= '</center>';

        return $this->content;
    }

    // updates and caches the content
    function update_cache()
    {
        global $CFG;

        // retrieve RSS feed
        $rss_fp = fopen('http://www.peopleofwalmart.com/?feed=rss2', 'r');
        $rss_content = '';
        while (!feof($rss_fp)) {
            $rss_content .= fread($rss_fp, 8192);
        }
        fclose($rss_fp);
        unset($rss_fp);

        // replace some annoying entities
        $this->filter_entities($rss_content);

        // extract the info we want
        preg_match_all('/<item>.*'.
            '<title>([^<>]+)<\/title>.*'.
            '<link>(http:\/\/www\.peopleofwalmart\.com\/[a-z0-9?=&%]+)<\/link>.*'.
            '<description><!\[CDATA\[(.*)\]\]><\/description>.*'.
            '<content:encoded><!\[CDATA\[.*<img[^<>]*'.
            '(http:\/\/media\.peopleofwalmart\.com\/wp-content\/uploads\/[a-z0-9\/]+\.jpg)'.
            '.*\]\]><\/content:encoded>.*'.
            '<\/item>/imsU', $rss_content, $rss_parts, PREG_PATTERN_ORDER);
        unset($rss_content);

        // create the cache directory if necessary
        @mkdir($this->cache_dir);

        // open the cache file for writing and truncate it, or create it if necessary
        $cache_fp = fopen($this->cache_html_file, 'w');

        // write the HTML content to the cache file
        for ($i = 0; $i < count($rss_parts[0]); $i++) {
            $rss_parts[3][$i] = trim($rss_parts[3][$i], ' /'.chr(10).chr(13));
            $rss_parts[3][$i] = preg_replace('/[\r\n]+/', ' —&nbsp;', $rss_parts[3][$i]);
            $rss_parts[4][$i] = $CFG->wwwroot.
                '/blocks/peopleofwalmart/block_peopleofwalmart_thumbnail.php?img='.
                urlencode($rss_parts[4][$i]);
            fwrite($cache_fp, 
                '<a target="_blank" href="'.$rss_parts[2][$i].'">'.
                '<b>'.$rss_parts[1][$i].'</b>'.
                '<img alt="" title="'.$rss_parts[3][$i].'" src="'.$rss_parts[4][$i].'" />'.
                '</a><span class="block_peopleofwalmart_caption">'.
                str_replace(' —&nbsp;', '<br />', $rss_parts[3][$i]).'</span>'.
                chr(10));
        }
        fclose($cache_fp);
        unset($cache_fp);

        $thumbnail_expiration = time() - $this->thumbnail_cache_time;
        if ($dh = @opendir($this->cache_dir.'/images')) {
            while (FALSE !== ($file = readdir($dh))) {
                if ($file != '.' && $file != '..'
                    && filemtime($this->cache_dir.'/images/'.$file) < $thumbnail_expiration
                ) {
                    @unlink($this->cache_dir.'/images/'.$file);
                }
            }
            closedir($dh);
            unset($dh, $file);
        }
        unset($thumbnail_expiration);
    }

    function filter_entities(&$string)
    {
        $entities = array(
            8216 => '\'',
            8217 => '\'',
            8220 => '&quot;',
            8221 => '&quot;',
            8230 => '...',
        );
        foreach ($entities as $num => $char) {
            $string = str_replace('&#'.$num.';', $char, $string);
        }
        unset($entities);

        return TRUE;
    }

    function cron()
    {
        // we're going to time how long it takes
        $starttime = microtime();

        // update and cache content
        $this->update_cache();

        // calculate how long it took
        $timeittook = microtime_diff($starttime, microtime());

        // output some info
        mtrace('');  // empty line, for cleanliness
        mtrace('People Of Walmart content updated and cached in '.$timeittook.' seconds.');

        return TRUE;
    }

}

?>